#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define MAX_CLIENTS 10

int main() {
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("socket");
        exit(1);
    }

    // 设置为非阻塞
    fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFL, 0) | O_NONBLOCK);

    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_addr.s_addr = INADDR_ANY,
        .sin_port = htons(8080)
    };

    if (bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        perror("bind");
        exit(1);
    }

    listen(sockfd, 5);
    printf("Non-blocking server listening on port 8080...\n");

    int client_fds[MAX_CLIENTS] = {0};

    while (1) {
        int client_fd = accept(sockfd, NULL, NULL);
        if (client_fd >= 0) {
            fcntl(client_fd, F_SETFL, fcntl(client_fd, F_GETFL, 0) | O_NONBLOCK);
            for (int i = 0; i < MAX_CLIENTS; i++) {
                if (client_fds[i] == 0) {
                    client_fds[i] = client_fd;
                    printf("New client: %d\n", client_fd);
                    break;
                }
            }
        }

        for (int i = 0; i < MAX_CLIENTS; i++) {
            int fd = client_fds[i];
            if (fd == 0) continue;

            char buffer[1024];
            ssize_t n = recv(fd, buffer, sizeof(buffer), 0);
            if (n > 0) {
                send(fd, buffer, n, 0);
            } else if (n == 0 || (n < 0 && errno != EWOULDBLOCK)) {
                close(fd);
                client_fds[i] = 0;
            }
        }
        usleep(100000);
    }

    close(sockfd);
    return 0;
}
